/**
 * Created with  SublimeText
 * @Author:      Lyle
 * @DateTime:    2016-12-06 10:19:40
 * @Description: 
 */

define(function(require, exports, module) {

    var tpl = require('{base}/tpls/myProfileProfile.tpl');

    var component = {

        template: _.template(tpl),

        render: function(page, obj) {
            this.page = page;
            return this.template(this.getTplData());
        },

        componentMount: function() {
            this.bindEvt();
            this.myProfileProfileRender();
        },

        componentUpdate: function() {

        },

        bindEvt: function() {

            var tthis = this,
                Dom = $('#' + this.page.id).find('.tabBox').find('div[tabname=\'myProfileProfile\']');

            Dom.on('click', '.infoKey .edit', function() {
                var keyName = $(this).parents('.infoKey').attr('keyname');
                tthis.switchKeyEdit(keyName);
            });

            Dom.on('click', '.infoKey .btnSave', function() {
                if ($(this).hasClass('btnDisabled')) {
                    return false;
                }
                var keyName = $(this).parents('.infoKey').attr('keyname');
                tthis.ajaxPostUserInfo(keyName);
            });

            Dom.on('click', '.infoKey .btnCancel', function() {
                var keyName = $(this).parents('.infoKey').attr('keyname');
                tthis.switchKeyRead(keyName);
            });

            Dom.on('input', '.infoKey *[listenInput=true]', function() {
                var lengthDom = $(this).parent().find('.annotation').find('.length');
                if (lengthDom.length > 0) {
                    var maxlength = $(this).attr('maxlength'),
                        minlength = $(this).attr('minlength'),
                        btnSave = $(this).closest('.profileEdit').find('.btnSave'),
                        nums = parseInt(maxlength) - $(this).val().length;
                    console.log(maxlength, nums);
                    lengthDom.html(nums > 0 ? nums : 0);
                    if (typeof(minlength) != 'undefined' && $(this).val().length < minlength) {
                        btnSave.addClass('btnDisabled');
                    } else {
                        btnSave.removeClass('btnDisabled');
                    }
                }
            });

            Dom.on('change', 'select[name=ageMonth]', function() {
                tthis.resetAgeDay($('select[name=ageDay]'), $('select[name=ageMonth]'), $('select[name=ageYear]'));
            });

            Dom.on('change', 'select[name=ageYear]', function() {
                tthis.resetAgeDay($('select[name=ageDay]'), $('select[name=ageMonth]'), $('select[name=ageYear]'));
            });

            Dom.on('change', 'select[name=matchAgeMin]', function() {
                tthis.resetMatchAge('min');
            });

            Dom.on('change', 'select[name=matchAgeMax]', function() {
                tthis.resetMatchAge('max');
            });
        },

        getTplData: function() {
            var obj = {
                userInfo: JSON.parse(Util.getSessionStorage('userInfo')),
                userStatus: JSON.parse(Util.getSessionStorage('userStatus'))
            }
            return obj;
        },

        ajaxPostUserInfo: function(keyName) {
            var tthis = this,
                postUserInfo = tthis[keyName + 'GetVal']();
            var callback = function(data) {
                if (data.results) {
                    tthis[keyName + 'SetVal'](data.data);
                    this.switchKeyRead(keyName);
                    this.affectOtherChange(keyName);
                }
            };
            Share.updateProfile(postUserInfo, callback.bind(this));
        },

        myProfileProfileRender: function() {
            var tthis = this,
                Dom = $('#' + this.page.id).find('.tabBox').find('div[tabname=\'myProfileProfile\']');
            Dom.find('.infoKey').each(function() {
                var keyName = $(this).attr('keyName');
                tthis.switchKeyRead(keyName);
            })
        },

        switchKeyRead: function(name) {
            var html = this.createDom(name, 'Read'),
                Dom = $('#' + this.page.id).find('.tabBox').find('div[tabname=\'myProfileProfile\']'),
                readDom = Dom.find('*[keyName=\'' + name + '\']').find('.profileRead'),
                editDom = Dom.find('*[keyName=\'' + name + '\']').find('.profileEdit');
            readDom.html(html);
            readDom.show();
            editDom.hide();
        },

        switchKeyEdit: function(name) {
            var html = this.createDom(name, 'Edit'),
                Dom = $('#' + this.page.id).find('.tabBox').find('div[tabname=\'myProfileProfile\']'),
                readDom = Dom.find('*[keyName=\'' + name + '\']').find('.profileRead'),
                editDom = Dom.find('*[keyName=\'' + name + '\']').find('.profileEdit');
            editDom.html(html);
            editDom.show();
            readDom.hide();
        },

        createDom: function(name, type) {
            if (this[name + type]) {
                return this[name + type]();
            } else {
                console.log(name + type + 'function not fonund!');
            }
        },

        headlineRead: function() {
            var userData = this.getTplData();
            if (typeof(userData) != 'undefined' && userData != null) {
                var headline = userData.userInfo.about.headline,
                    html = '<h3>' + Lang.myProfileHeadline + ' <span class="edit"></span></h3><div class="infoContent">' + headline + '</div>';
                return html;
            }
        },

        headlineEdit: function() {
            var userData = this.getTplData();
            console.log(this.page);
            if (typeof(userData) != 'undefined' && userData != null) {
                var headline = userData.userInfo.about.headline,
                    html = '<h3>' + Lang.myProfileHeadline + ': </h3><input listenInput=true name="title" maxlength="100" minlength="10" value="' + headline + '" type="text" placeholder="' + Lang.myProfileHeadlinePlaceholder + '" /><div class="annotation"><strong class="length">' + (100 - headline.length) + '</strong> ' + Lang.myProfileHeadlineAnnotation + '</div><div class="submitBox"><div class="btnCancel cancel">' + Lang.unifyCancel + '</div><div class="btn btnSave save">' + Lang.unifySave + '</div></div>';
                return html;
            }
        },

        headlineGetVal: function() {
            var userInfo = {
                'title': $('#' + this.page.id).find('*[keyName=\'headline\']').find('.profileEdit').find('input').val(),
            };
            return userInfo;
        },

        headlineSetVal: function(data) {
            var userInfo = JSON.parse(Util.getSessionStorage('userInfo'));
            userInfo.about.headline = data.title;
            Util.setSessionStorage('userInfo', JSON.stringify(userInfo));
        },

        ageRead: function() {
            var userData = this.getTplData().userInfo;
            if (typeof(userData) != 'undefined' && userData != null) {
                var ageData = {
                        'age': userData.account.age,
                        'matchAgeMin': userData.match.match_age_min,
                        'matchAgeMax': userData.match.match_age_max,
                    },
                    html = '<div class="w1"><div class="nrbox"><h3>' + Lang.unifyAge + ' <span class="edit"></span></h3></div></div><div class="w2"><div class="nrbox">' + ageData.age + '</div></div><div class="w3"><div class="nrbox">From ' + ageData.matchAgeMin + ' to ' + ageData.matchAgeMax + '</div></div>';
                return html;
            }

        },


        ageEdit: function() {
            var userData = this.getTplData().userInfo;
            if (typeof(userData) != 'undefined' && userData != null) {
                var month = parseInt(userData.detail.basics.age_month),
                    day = parseInt(userData.detail.basics.age_day),
                    year = parseInt(userData.detail.basics.age_year),
                    matchAgeMin = userData.match.match_age_min,
                    matchAgeMax = userData.match.match_age_max,
                    dayHtml = '<select name=ageDay>' + Share.getDayStr(year, month, day) + '</select>',
                    monHtml = '<select name=ageMonth>' + Share.getMonthStr(month) + '</select>',
                    yearHtml = '<select name=ageYear>' + Share.getYearStr(((new Date()).getFullYear() - 100), (new Date()).getFullYear(), year) + '</select>',
                    html = '<div class=w1><div class=nrbox><h3>' + Lang.unifyAge + '</h3></div></div><div class=w2><div class=nrbox><dl class=itemOne><dd>' + Lang.unifyMonth + '</dd><dd>' + monHtml + '</dd></dl><dl class=itemOne><dd>' + Lang.unifyDay + '</dd><dd>' + dayHtml + '</dd></dl><dl class=itemOne><dd>' + Lang.unifyYear + '</dd><dd>' + yearHtml + '</dd></dl></div></div><div class="w3"><div class="nrbox"><dl class="itemOne"><dd>' + Lang.unifyFrom + '</dd><dd><select name="matchAgeMin">' + Share.getMatchAgeStr(matchAgeMin) + '</select></dd></dl><dl class="itemOne"><dd>' + Lang.unifyTo + '</dd><dd><select name="matchAgeMax">' + Share.getMatchAgeStr(matchAgeMax) + '</select></dd></dl></div></div><div class=submitBox><div class="btnCancel cancel">' + Lang.unifyCancel + '</div><div class="btn btnSave save">' + Lang.unifySave + '</div></div>';
                return html;
            }
        },

        ageGetVal: function() {
            var editDom = $('#' + this.page.id).find('*[keyName=\'age\']').find('.profileEdit');
            var userInfo = {
                'age_day': editDom.find('select[name=ageDay]').val(),
                'age_month': editDom.find('select[name=ageMonth]').val(),
                'age_year': editDom.find('select[name=ageYear]').val(),
                'match_age_min': editDom.find('select[name=matchAgeMin]').val(),
                'match_age_max': editDom.find('select[name=matchAgeMax]').val(),
                'age': (new Date()).getFullYear() - editDom.find('select[name=ageYear]').val()
            };
            return userInfo;
        },

        ageSetVal: function(data) {
            var userInfo = JSON.parse(Util.getSessionStorage('userInfo'));
            console.log(userInfo);
            userInfo.account.age = data.age;
            userInfo.detail.basics.age_day = data.age_day;
            userInfo.detail.basics.age_month = data.age_month;
            userInfo.detail.basics.age_year = data.age_year;
            userInfo.match.match_age_min = data.match_age_min;
            userInfo.match.match_age_max = data.match_age_max;
            Util.setSessionStorage('userInfo', JSON.stringify(userInfo));
        },

        resetAgeDay: function(dayDom, monthDom, yearDom) {
            var day = dayDom.val(),
                month = monthDom.val(),
                year = yearDom.val();
            if (parseInt(day) > parseInt(new Date(year, month, 0).getDate())) {
                day = 1;
            };
            dayDom.html('<select name=ageDay>' + Share.getDayStr(year, month, day) + '</select>');
        },

        resetMatchAge: function(type) {
            var Dom = $('#' + this.page.id).find('.tabBox').find('div[tabname=\'myProfileProfile\']'),
                ageMin = Dom.find('select[name=matchAgeMin]'),
                ageMax = Dom.find('select[name=matchAgeMax]');
            if (parseInt(ageMin.val()) > parseInt(ageMax.val())) {
                if ($.trim(type).toLowerCase() == 'min') {
                    ageMax.val(ageMin.val());
                } else if ($.trim(type).toLowerCase() == 'max') {
                    ageMin.val(ageMax.val());
                }

            }
        },

        relationshipRead: function() {
            var userData = this.getTplData().userInfo;
            if (typeof(userData) != 'undefined' && userData != null) {
                var marital = {
                        'marital': userData.about.relationship_status,
                        'matchMarital': userData.match.match_marital,
                    },
                    html = '<div class="w1"><div class="nrbox"><h3>' + Lang.myProfileRelationship + '<span class="edit"></span></h3></div></div><div class="w2"><div class="nrbox">' + Share.getSelectLabel('ms_marital', marital.marital, Lang.noPreference, 'font4') + '</div></div><div class="w3"><div class="nrbox">' + Share.getCheckboxLabel('ms_marital', marital.matchMarital, '; ', Lang.noPreference, 'font4') + '</div></div>';
                return html;
            }
        },

        relationshipEdit: function() {
            var userData = this.getTplData().userInfo;
            if (typeof(userData) != 'undefined' && userData != null) {
                var marital = {
                        'marital': userData.about.relationship_status,
                        'matchMarital': userData.match.match_marital,
                    },
                    html = '<div class="w1"><div class="nrbox"><h3>' + Lang.myProfileRelationship + '</h3></div></div><div class="w2"><div class="nrbox"><select name="marital">' + Share.getSelectHtml('ms_marital', marital.marital) + '</select></div></div><div class="w3"><div class="nrbox"><dl class="itemOne">' + Share.getCheckboxHtml('ms_marital', marital.matchMarital, 'matchMarital') + '</dl></div></div><div class=submitBox><div class="btnCancel cancel">' + Lang.unifyCancel + '</div><div class="btn btnSave save">' + Lang.unifySave + '</div></div>';
                return html;
            }
        },

        relationshipGetVal: function() {
            var editDom = $('#' + this.page.id).find('*[keyName=\'marital\']').find('.profileEdit');
            var userInfo = {
                'relationship_status': editDom.find('select[name=marital]').val(),
                'match_marital': Share.getCheckboxData(editDom.find('input[name=matchMarital]')),
            };
            return userInfo;
        },

        relationshipSetVal: function(data) {
            var userInfo = JSON.parse(Util.getSessionStorage('userInfo'));
            console.log(userInfo);
            userInfo.about.relationship_status = data.relationship_status;
            userInfo.match.match_marital = data.match_marital;
            Util.setSessionStorage('userInfo', JSON.stringify(userInfo));
            this.page.setBaseAge();
        },

        incomeRead: function() {
            var userData = this.getTplData().userInfo;
            if (typeof(userData) != 'undefined' && userData != null) {
                var type = {
                        'type': userData.detail.worth.income,
                        'matchType': userData.match.match_type,
                    },
                    html = '<div class="w1"><div class="nrbox"><h3>' + Lang.AnnualIncome + '<span class="edit"></span></h3></div></div><div class="w2"><div class="nrbox">' + Share.getSelectLabel('ms_type', type.type, Lang.noPreference, 'font4') + '</div></div><div class="w3"><div class="nrbox">' + Share.getSelectLabel('ms_type', type.matchType, Lang.noPreference, 'font4') + '</div></div>';
                return html;
            }
        },

        incomeEdit: function() {
            var userData = this.getTplData().userInfo;
            if (typeof(userData) != 'undefined' && userData != null) {
                var type = {
                        'type': userData.detail.worth.income,
                        'matchType': userData.match.match_type,
                    },
                    html = '<div class="w1"><div class="nrbox"><h3>' + Lang.AnnualIncome + '</h3></div></div><div class="w2"><div class="nrbox"><select name="type">' + Share.getSelectHtml('ms_type', type.type) + '</select></div></div><div class="w3"><div class="nrbox"><select name="matchType">' + Share.getSelectHtml('ms_type', type.matchType) + '</select></div></div><div class=submitBox><div class="btnCancel cancel">' + Lang.unifyCancel + '</div><div class="btn btnSave save">' + Lang.unifySave + '</div></div>';
                return html;
            }
        },

        incomeGetVal: function() {
            var editDom = $('#' + this.page.id).find('*[keyName=\'type\']').find('.profileEdit');
            var userInfo = {
                'income': editDom.find('select[name=type]').val(),
                'match_type': editDom.find('select[name=matchType]').val(),
            };
            return userInfo;
        },

        incomeSetVal: function(data) {
            var userInfo = JSON.parse(Util.getSessionStorage('userInfo'));
            console.log(userInfo);
            userInfo.detail.worth.income = data.income;
            userInfo.match.match_type = data.match_type;
            Util.setSessionStorage('userInfo', JSON.stringify(userInfo));
            this.page.setBaseAge();
        },

        affectOtherChange: function(typeString) {
            if (this.page.myProfileProfileComponentChange) {
                this.page.myProfileProfileComponentChange(typeString);
            }
        },
    }

    module.exports = component;
});
